<template>
  <div class="notification-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>通知中心</h2>
      <div class="header-actions">
        <el-button @click="markAllAsRead" :disabled="unreadCount === 0">全部标记为已读</el-button>
        <el-button @click="refreshNotifications">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="stats-card stats-total" shadow="hover">
          <div class="stats-card-content">
            <div class="stats-value">{{ statistics.total }}</div>
            <div class="stats-label">总通知</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="stats-card stats-unread" shadow="hover">
          <div class="stats-card-content">
            <div class="stats-value">{{ statistics.unread }}</div>
            <div class="stats-label">未读通知</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="stats-card stats-task" shadow="hover">
          <div class="stats-card-content">
            <div class="stats-value">{{ statistics.tasks }}</div>
            <div class="stats-label">待处理任务</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="stats-card stats-urgent" shadow="hover">
          <div class="stats-card-content">
            <div class="stats-value">{{ statistics.urgent }}</div>
            <div class="stats-label">紧急通知</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :model="filterForm" inline>
        <el-form-item label="通知类型">
          <el-select v-model="filterForm.type" placeholder="全部" clearable>
            <el-option label="任务分配" value="task_assignment"></el-option>
            <el-option label="系统通知" value="system"></el-option>
            <el-option label="预警提醒" value="alert"></el-option>
            <el-option label="审批通知" value="approval"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable>
            <el-option label="未读" value="unread"></el-option>
            <el-option label="已读" value="read"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="filterForm.priority" placeholder="全部" clearable>
            <el-option label="紧急" value="urgent"></el-option>
            <el-option label="重要" value="important"></el-option>
            <el-option label="普通" value="normal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchNotifications">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知列表 -->
    <el-card class="notification-list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>通知列表</span>
          <div class="header-actions">
            <el-button size="small" type="danger" @click="batchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="notificationTable"
        :data="notificationList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        row-class-name="notification-row"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.priority === 'urgent' ? 'danger' :
                scope.row.priority === 'important' ? 'warning' : 'info'
              "
              size="small"
            >
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <div class="notification-title" :class="{ 'unread': !scope.row.is_read }">
              <el-icon v-if="!scope.row.is_read" class="unread-icon"><CircleFilled /></el-icon>
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="250" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sender_name" label="发送人" width="100"></el-table-column>
        <el-table-column prop="created_at" label="时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click.stop="viewNotification(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click.stop="handleTask(scope.row)"
              v-if="scope.row.type === 'task_assignment' && scope.row.task_status !== 'completed'"
            >
              处理任务
            </el-button>
            <el-button 
              size="small" 
              @click.stop="markAsRead(scope.row)"
              v-if="!scope.row.is_read"
            >
              标记已读
            </el-button>
            <el-button size="small" type="danger" @click.stop="deleteNotification(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleFilled } from '@element-plus/icons-vue'
import {
  getNotificationList,
  getNotificationStatistics,
  markNotificationAsRead,
  markAllAsRead as markAllAsReadApi,
  deleteNotification as deleteNotificationApi,
  batchDeleteNotifications
} from '@/api/modules/notification'

const router = useRouter()

// 加载状态
const loading = ref(false)

// 表格引用
const notificationTable = ref(null)

// 筛选表单
const filterForm = reactive({
  type: '',
  status: '',
  priority: '',
  timeRange: []
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 统计数据
const statistics = reactive({
  total: 0,
  unread: 0,
  tasks: 0,
  urgent: 0
})

// 通知列表
const notificationList = ref([])

// 选中的行
const selectedRows = ref([])

// 计算未读数量
const unreadCount = computed(() => {
  return notificationList.value.filter(item => !item.is_read).length
})

// 获取优先级文本
const getPriorityText = (priority) => {
  const map = {
    urgent: '紧急',
    important: '重要',
    normal: '普通'
  }
  return map[priority] || '普通'
}

// 获取类型文本
const getTypeText = (type) => {
  const map = {
    task_assignment: '任务分配',
    system: '系统通知',
    alert: '预警提醒',
    approval: '审批通知'
  }
  return map[type] || '系统通知'
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const map = {
    task_assignment: 'primary',
    system: 'info',
    alert: 'warning',
    approval: 'success'
  }
  return map[type] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取通知列表
const fetchNotifications = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }

    // 添加筛选条件
    if (filterForm.type) params.type = filterForm.type
    if (filterForm.status) params.status = filterForm.status
    if (filterForm.priority) params.priority = filterForm.priority
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      params.start_date = filterForm.timeRange[0]
      params.end_date = filterForm.timeRange[1]
    }

    console.log('请求通知列表参数:', params)
    const response = await getNotificationList(params)
    console.log('通知列表响应:', response)

    if (response && response.success) {
      notificationList.value = response.results || response.data || []
      pagination.total = response.count || response.total || 0
      console.log('通知列表数据:', notificationList.value)
    } else {
      // 如果API调用失败，使用模拟数据
      const mockData = [
        {
          id: 1,
          type: 'task_assignment',
          priority: 'urgent',
          title: '客户流失挽回任务分配',
          content: '您被分配了一个高风险客户的流失挽回任务，客户ID: C001，请及时处理。',
          sender_name: '系统管理员',
          is_read: false,
          task_status: 'pending',
          task_id: 'T001',
          alert_id: 1,
          created_at: '2023-12-01 10:30:00'
        },
        {
          id: 2,
          type: 'alert',
          priority: 'important',
          title: '新增高风险客户预警',
          content: '检测到新的高风险客户，流失概率达到85%，建议立即关注。',
          sender_name: '预警系统',
          is_read: true,
          created_at: '2023-12-01 09:15:00'
        },
        {
          id: 3,
          type: 'system',
          priority: 'normal',
          title: '系统维护通知',
          content: '系统将于今晚22:00-24:00进行维护，期间可能影响部分功能使用。',
          sender_name: '系统管理员',
          is_read: false,
          created_at: '2023-11-30 16:45:00'
        }
      ]

      notificationList.value = mockData
      pagination.total = mockData.length
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await getNotificationStatistics()

    if (response.success && response.data) {
      Object.assign(statistics, response.data)
    } else {
      // 如果API调用失败，使用本地计算
      statistics.total = notificationList.value.length
      statistics.unread = notificationList.value.filter(item => !item.is_read).length
      statistics.tasks = notificationList.value.filter(item => item.type === 'task_assignment' && item.task_status !== 'completed').length
      statistics.urgent = notificationList.value.filter(item => item.priority === 'urgent').length
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用本地计算作为后备
    statistics.total = notificationList.value.length
    statistics.unread = notificationList.value.filter(item => !item.is_read).length
    statistics.tasks = notificationList.value.filter(item => item.type === 'task_assignment' && item.task_status !== 'completed').length
    statistics.urgent = notificationList.value.filter(item => item.priority === 'urgent').length
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理行点击
const handleRowClick = (row) => {
  if (!row.is_read) {
    markAsRead(row)
  }
}

// 查看通知详情
const viewNotification = (row) => {
  ElMessageBox.alert(row.content, row.title, {
    confirmButtonText: '确定',
    type: row.priority === 'urgent' ? 'error' : row.priority === 'important' ? 'warning' : 'info'
  })

  if (!row.is_read) {
    markAsRead(row)
  }
}

// 处理任务
const handleTask = (row) => {
  if (row.type === 'task_assignment' && row.alert_id) {
    // 跳转到预警管理页面，并定位到对应的预警
    router.push({
      path: '/prediction/alert',
      query: { alertId: row.alert_id }
    })
  } else {
    ElMessage.info('任务详情功能开发中...')
  }
}

// 标记为已读
const markAsRead = async (row) => {
  try {
    const response = await markNotificationAsRead(row.id)

    if (response.success) {
      row.is_read = true
      ElMessage.success('已标记为已读')
      fetchStatistics()
    } else {
      ElMessage.error(response.message || '标记已读失败')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    // 如果API调用失败，仍然更新本地状态
    row.is_read = true
    fetchStatistics()
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  try {
    const response = await markAllAsReadApi()

    if (response.success) {
      notificationList.value.forEach(item => {
        item.is_read = true
      })
      ElMessage.success('已全部标记为已读')
      fetchStatistics()
    } else {
      ElMessage.error(response.message || '批量标记已读失败')
    }
  } catch (error) {
    console.error('批量标记已读失败:', error)
    // 如果API调用失败，仍然更新本地状态
    notificationList.value.forEach(item => {
      item.is_read = true
    })
    fetchStatistics()
  }
}

// 删除通知
const deleteNotification = (row) => {
  ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteNotificationApi(row.id)

      if (response.success) {
        const index = notificationList.value.findIndex(item => item.id === row.id)
        if (index > -1) {
          notificationList.value.splice(index, 1)
        }
        ElMessage.success('删除成功')
        fetchStatistics()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除通知失败:', error)
      // 如果API调用失败，仍然删除本地数据
      const index = notificationList.value.findIndex(item => item.id === row.id)
      if (index > -1) {
        notificationList.value.splice(index, 1)
        fetchStatistics()
      }
    }
  }).catch(() => {})
}

// 批量删除
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的通知')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条通知吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const selectedIds = selectedRows.value.map(row => row.id)
      const response = await batchDeleteNotifications(selectedIds)

      if (response.success) {
        notificationList.value = notificationList.value.filter(item => !selectedIds.includes(item.id))
        notificationTable.value?.clearSelection()
        ElMessage.success('批量删除成功')
        fetchStatistics()
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      // 如果API调用失败，仍然删除本地数据
      const selectedIds = selectedRows.value.map(row => row.id)
      notificationList.value = notificationList.value.filter(item => !selectedIds.includes(item.id))
      notificationTable.value?.clearSelection()
      fetchStatistics()
    }
  }).catch(() => {})
}

// 刷新通知
const refreshNotifications = () => {
  fetchNotifications()
  fetchStatistics()
  ElMessage.success('刷新成功')
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    type: '',
    status: '',
    priority: '',
    timeRange: []
  })
  fetchNotifications()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchNotifications()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchNotifications()
}



// 生命周期钩子
onMounted(() => {
  fetchNotifications()
  fetchStatistics()
})
</script>

<style scoped>
.notification-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-card-content {
  padding: 10px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.stats-total .stats-value { color: #409EFF; }
.stats-unread .stats-value { color: #E6A23C; }
.stats-task .stats-value { color: #67C23A; }
.stats-urgent .stats-value { color: #F56C6C; }

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-title.unread {
  font-weight: bold;
  color: #303133;
}

.unread-icon {
  color: #409EFF;
  font-size: 8px;
}

.notification-row {
  cursor: pointer;
}

.notification-row:hover {
  background-color: #f5f7fa;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
